#include "streamAccess.hpp"
#include "exceptions.hpp"

namespace hms
{

std::ofstream getWriteFile( const fs::path& path, bool binary )
{
	std::ofstream writeFile {
		path.c_str(),
		( binary? 
			std::ios::binary :
			std::ios::binary &~std::ios::binary ) |
		std::ios::trunc // delete all current content
	};
	
	if (!writeFile)
	{
		throw FileError(
			"Could not write to file \"" + path.string() + "\"!"
		);
	}
	
	return writeFile;
}


std::ifstream getReadFile( const fs::path& path, bool binary )
{
	/* bitset & ~bitset produces all zeros. Used to turn off binary mode */
	std::ifstream readFile {
		path.c_str(),
		( binary? 
			std::ios::binary :
			std::ios::binary &~std::ios::binary )
	};
	
	if (!readFile)
	{
		throw FileError(
			"Could not read file \"" + path.string() + "\"!"
		);
	}
	
	return readFile;
}


std::string getWord( std::istream& stream )
{
	/* ignore leading whitespace */
	stream >> std::ws;
	
	std::string word;
	while ( stream )
	{
		if ( isalpha( stream.peek() ) )
			word += stream.get();
		else
			break;
	}
	
	/* reset stream state if end of stream has been reached */
	if (stream.eof())
	{
		stream.clear();
	}
	return word;
}

bool getUserChoice(){
	std::string line;
	while (true){
		std::cout << "[Y/n]: ";
		std::getline( std::cin, line );
		if ( line.empty() || line == "y" || line == "Y" )
			return true;
		else if ( line == "n" || line == "N" )
			return false;
		if ( std::cin.fail() )
			std::cin.clear();
	}
}
	
} // end namespace hms
